package dproxy.application.ui.commands;

import java.util.Collection;
import java.util.Iterator;

import dproxy.application.ui.CommandLineProcessor;
import dproxy.server.cache.dao.DatabaseImplentation;

/**
 * Changes database implementation.
 */
public class Switch implements Command {

    /** Sub-Command that switches database implementation. */
    private static final String SC_DATABASE = "database";
        
    /** Sub command (command option). */
    private String subCommand;

    /**
     * @see dproxy.application.ui.commands.Command#description()
     */
    public String description() {
        return 
            "   'switch database' \n" +
            "                  - Changes database implementation where commands will be\n" +
            "                    applyed";
    }

    /**
     * @see dproxy.application.ui.commands.Command#validate(Collection)
     */
    public void validate(Collection<String> parameters) throws ValidationException {
        
        Iterator <String> itParameters = parameters.iterator();
        if (itParameters.hasNext()) {
            subCommand = itParameters.next();
            if (SC_DATABASE.equals(subCommand)) {
                ValidationUtils.validateNoMoreParameters(itParameters);
            } else {
                throw new ValidationException();
            }
        } else {
            throw new ValidationException();
        }
        
    }

    /**
     * @see dproxy.application.ui.commands.Command#confirm()
     */
    public boolean confirm() {
        // Switch operation needs no confirmation
        return true;
    }

    /**
     * @see dproxy.application.ui.commands.Command#execute()
     */
    public void execute() {
        DatabaseImplentation cacheImplementation
            = CommandLineProcessor.getInstance().getCacheImplementation();
        String message = "Switched to ";
        if (SC_DATABASE.equals(subCommand)) {
            if (DatabaseImplentation.PERSISTENT.equals(cacheImplementation)) {
                CommandLineProcessor.getInstance().setCacheImplementation(
                        DatabaseImplentation.IN_MEMORY);
                message += "in-memory";
            } else {
                CommandLineProcessor.getInstance().setCacheImplementation(
                        DatabaseImplentation.PERSISTENT);
                message += "persistent";
            }
        }
        message += " database";
        CommandLineProcessor.getInstance().write(message);
    }

}
